package com.polaris.live.popup.party

import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.core.os.bundleOf
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.StringUtils
import com.bumptech.glide.Glide
import com.gyf.immersionbar.ImmersionBar
import com.polaris.live.R
import com.polaris.live.common.R.color
import com.polaris.live.common.adapter.ViewPagerAdapter
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.PopupRoomInfoSpectatorBinding
import com.polaris.live.manager.AppConfigManager
import com.polaris.live.net.liveService
import com.polaris.live.resp.back_resp.PartyRoomInfoResp
import com.polaris.live.resp.go_resp.FollowRoomRequest
import com.polaris.live.translation.R.string
import com.polaris.live.ui.party.fragment.roomInfo.MemberFragment
import com.polaris.live.ui.party.fragment.roomInfo.SpectatorRoomInfoFragment
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.image.transformRounded
import com.polaris.live.widget.pag.AddFollowView

/**
 * RoomInfoSpectatorPopup 观众查看房间信息
 *
 * @author Created by 天晴 on 2024/2/27 19:18
 * @since 1.0.0
 **/
class RoomInfoSpectatorPopup : DialogFragment() {

    private lateinit var mBinding: PopupRoomInfoSpectatorBinding

    private val mLiveId by lazy { arguments?.getLong("liveId") ?: 0 }
    private val mUserId by lazy { arguments?.getLong("userId") ?: 0 }
    private val mRoomId by lazy { arguments?.getString("roomId") ?: "" }
    private val mVipLevel by lazy { arguments?.getLong("vipLevel") }
    private val mRoomTheme by lazy { arguments?.getString("roomTheme") ?: "" }

    private var mViewPagerAdapter: ViewPagerAdapter? = null

    private var mOnAvClickListener: ((userId: Long) -> Unit)? = null
    private var mOnFollowedBackListener: ((followed: Boolean) -> Unit)? = null

    private val mSpectatorRoomInfoFragment by lazy {
        SpectatorRoomInfoFragment().apply {
            arguments = bundleOf(
                "userId" to mUserId,
                "roomId" to mRoomId
            )
            setListener {
                dismiss()
                mOnAvClickListener?.invoke(mUserId)
            }
            setOnJoinMemberCallback {
                if (it) {
                    this@RoomInfoSpectatorPopup.mBinding.memberLl.visibility = View.VISIBLE
                    mViewPagerAdapter?.addFragment(mMemberFragment)
                } else {
                    this@RoomInfoSpectatorPopup.mBinding.memberLl.visibility = View.INVISIBLE
                    mViewPagerAdapter?.removeFragment(mViewPagerAdapter?.itemCount?.minus(1) ?: 1)
                }
            }
        }
    }
    private val mMemberFragment
        get() =
            MemberFragment().apply {
                arguments = bundleOf(
                    "roomId" to mRoomId
                )
                setListener {
                    dismiss()
                    mOnAvClickListener?.invoke(it)
                }
            }

    private var mPartyRoomInfoResp: PartyRoomInfoResp? = null

    private var followed = false

    private val mViewModel by viewModels<BaseViewModel>()

    override fun onStart() {
        super.onStart()
        dialog?.window?.apply {
            setWindowAnimations(R.style.BottomDialogAnimation)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        mBinding = PopupRoomInfoSpectatorBinding.inflate(inflater, container, false)
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .navigationBarDarkIcon(true)
            .transparentNavigationBar()
            .init()
        initView()
        val bottomView = mBinding.bottom
        val lp = bottomView.layoutParams as ViewGroup.LayoutParams
        lp.height = NavigationBarUtils.getNavigationBarHeight(requireContext())
        bottomView.layoutParams = lp
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = Dialog(requireContext(), android.R.style.Theme_Light_NoTitleBar_Fullscreen)
        val window = dialog.window
        window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        return dialog
    }

    fun initView() {
        getData()
        initListener()

        val themeData = AppConfigManager.getUserTheme(mRoomTheme)
        themeData?.let {
            mBinding.consCenter.setBackgroundResource(0)
            mBinding.ivRoomInfoBack.visibility = View.VISIBLE
            mBinding.ivRoomInfoBack.shapeDrawableBuilder
                .setSolidGradientColors(Color.parseColor(it.listStartColor), Color.parseColor(it.listEndColor))
                .intoBackground()
            Glide.with(requireContext()).load(ImageUtils.imgPath(it.listIcon)).into(mBinding.ivSkinIcon)
            mBinding.ivSkinIcon.alpha = it.listAlpha?.div(100f) ?: 0.3f
        }
    }

    private fun getData() {
        mViewModel.requestLoading(
            { liveService.getPartyRoomInfo(mLiveId) }, {
                mPartyRoomInfoResp = it
                setDataView(it)
            },
            { ToastGravity.showGravity(it.errorMsg) }
        )
    }

    private fun unFollowRoom() {
        mViewModel.requestLoading(
            { liveService.unFollowRoom(mUserId) }, {
                ToastGravity.showGravity(string.cancel_follower)
                followed = false
                mOnFollowedBackListener?.invoke(false)
                followed()
            },
            { ToastGravity.showGravity(it.errorMsg) }
        )
    }

    private fun addFollowRoom() {
        mViewModel.requestLoading(
            { liveService.followRoom(FollowRoomRequest(mUserId)) },
            {
                ToastGravity.showGravity(string.follower_succeed)
                followed = true
                mOnFollowedBackListener?.invoke(true)
                followed()
            },
            { ToastGravity.showGravity(it.errorMsg) }
        )
    }

    private fun setDataView(mPartyRoomInfoResp: PartyRoomInfoResp) {
        mSpectatorRoomInfoFragment.setDataView(mPartyRoomInfoResp)
        mBinding.apply {
            mainLl.visibility = View.VISIBLE
            widgetLoading.visibility = View.GONE
            Glide.with(requireContext())
                .load(ImageUtils.imgPath(mPartyRoomInfoResp.cover))
                .transformRounded(6.autoDp)
                .into(roomImg)
            roomName.text = mPartyRoomInfoResp.roomName
            roomId.text = StringUtils.getString(string.id, mPartyRoomInfoResp.roomNumber)
            followersNumber.text =
                "${StringUtils.getString(string.followers_people)}:${mPartyRoomInfoResp.follower}"
            memberNumber.text = "${getString(string.member)}:${mPartyRoomInfoResp.member}"
            roomFrame.setRoomFrame(mPartyRoomInfoResp.user.roomFrame)

            followed = mPartyRoomInfoResp.followed
            followed()
        }
        val mFragments = buildList {
            add(mSpectatorRoomInfoFragment)
            if (mPartyRoomInfoResp.isMember) {
                mBinding.memberLl.visibility = View.VISIBLE
                add(mMemberFragment)
            }
        }
        mViewPagerAdapter = ViewPagerAdapter(mFragments, this)
        mBinding.viewpager2.adapter = mViewPagerAdapter
        mBinding.viewpager2.currentItem = 0
    }

    private fun followed() {
        if (followed) {
            mBinding.pagView.visibility = View.GONE
            mBinding.followOk.visibility = View.VISIBLE
        } else {
            mBinding.pagView.visibility = View.VISIBLE
            mBinding.followOk.visibility = View.GONE
            mBinding.pagView.setPathType(AddFollowView.LIVE_ADD_FOLLOWE)
        }
    }

    private fun initListener() {
        mBinding.root.setOnSingleClickListener {
            dismiss()
        }
        mBinding.mainLl.setOnClickListener {
        }
        mBinding.followOk.setOnSingleClickListener {
            unFollowRoom()
        }
        mBinding.pagView.setOnSingleClickListener {
            addFollowRoom()
        }

        mBinding.informationLl.setOnSingleClickListener {
            setTab(0)
            mBinding.viewpager2.currentItem = 0
        }

        mBinding.memberLl.setOnSingleClickListener {
            setTab(1)
            mBinding.viewpager2.currentItem = 1
        }
        mBinding.viewpager2.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                setTab(position)
            }
        })
    }

    private fun setTab(index: Int) {
        when (index) {
            0 -> {
                mBinding.informationLine.visibility = View.VISIBLE
                mBinding.memberLine.visibility = View.GONE
                mBinding.textInformation.setTextColor(ColorUtils.getColor(R.color.white))
                mBinding.textMember.setTextColor(ColorUtils.getColor(color.color_80ffffff))
            }

            1 -> {
                mBinding.informationLine.visibility = View.GONE
                mBinding.memberLine.visibility = View.VISIBLE
                mBinding.textInformation.setTextColor(ColorUtils.getColor(color.color_80ffffff))
                mBinding.textMember.setTextColor(ColorUtils.getColor(R.color.white))
            }
        }
    }

    companion object {

        fun show(
            context: Fragment,
            liveId: Long,
            userId: Long,
            roomId: String,
            vipLevel: Long? = null,
            roomTheme: String? = null,
            avClick: ((userId: Long) -> Unit)?,
            followedBack: ((followed: Boolean) -> Unit)?,
        ) {
            val fragmentManager = context.parentFragmentManager
            RoomInfoSpectatorPopup()
                .apply {
                    arguments = bundleOf(
                        "liveId" to liveId,
                        "userId" to userId,
                        "roomId" to roomId,
                        "vipLevel" to vipLevel,
                        "roomTheme" to roomTheme
                    )
                    mOnAvClickListener = avClick
                    mOnFollowedBackListener = followedBack
                }.show(fragmentManager, "RoomInfoSpectatorPopup")
        }
    }
}